<?php

namespace app\index\controller;

use think\Db;

class User extends Common
{


    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 登录 \n
     * URI : /user/login
     * @param :
     *  name      |  type  | null | description
     * -----------|--------|------|-------------
     *  sign      | string | 必填  | 签名
     * user_name  | string | 必填  | 用户名
     *  user_pwd  | string | 必填  | 密码
     *
     * @return
     *    name      |  type   | description
     * -------------|---------|----------------------
     * -------------|-------- | -----------
     *
     */
    public function login()
    {
        $user_name = $this->_getParams('user_name');
        if (empty($user_name) === true) {
            $this->_returnError(20002, '用户名错误');
        }

        $user_pwd = $this->_getParams('user_pwd');
        if (empty($user_pwd) === true) {
            $this->_getParams(20003, "密码错误");
        }

        $user_info = Db::name('user_info')->where(['user_name'=>$user_name])->find();
        if(empty($user_info) === true) {
            $this->_returnError(20005,'无此用户');
        }

        if(md5($user_pwd) != $user_info['user_pwd']) {
            $this->_returnError(20006,'密码错误');
        }
        
        $this->_returnData(['passport' => $user_info['passport']]);
    }


    /**
     * 注册 \n
     * URI : /user/register
     * @param :
     *  name      |  type  | null | description
     * -----------|--------|------|-------------
     *  sign      | string | 必填  | 签名
     * user_name  | string | 必填  | 用户名
     *  user_pwd  | string | 必填  | 密码
     *
     * @return
     *    name      |  type   | description
     * -------------|---------|----------------------
     * -------------|-------- | -----------
     *
     */
    public function register()
    {
        $user_name = $this->_getParams('user_name');
        if (empty($user_name) === true) {
            $this->_returnError(20002, '用户名错误');
        }

        $user_pwd = $this->_getParams('user_pwd');
        if (empty($user_pwd) === true) {
            $this->_getParams(20003, "密码错误");
        }

        $result = \think\Db::name('user_info')->insert([
            'user_name' => $user_name,
            'user_pwd' => md5($user_pwd),
            'passport' => $this->_getRandomString(),
            'add_time' => $this->_now,
        ]);

        if ($result)
            $this->_returnData();
        $this->_returnError(20004, '注册失败');
    }
}
